/*
 * @Author: 消息逻辑
 */

'use strict';

YX.fn.message = function() {
  this.$sendBtn = $('#sendBtn');
  this.$messageText = $('#messageText');
  this.$chooseFileBtn = $('#chooseFileBtn');
  this.$fileInput = $('#uploadFile');
  this.$toRecord = $('#toRecord');
  this.$recordTimeBox = $('#toRecordBox')
  this.$recordTimeDuration = $('#toRecordTime')
  this.$cancelRecord = $('#toRecordCancle')
  this.$showNetcallAudioLink = $('#showNetcallAudioLink')
  this.$showNetcallVideoLink = $('#showNetcallVideoLink')
  this.$showWhiteboard = $('#showWhiteboard')

  this.$endserviceBtn = $('#endserviceBtn')
  this.$comonWordsWrap = $("#comonWordsWrap")

  this.$sendQuickOrderWrap = $('#sendQuickOrderWrap')

  //剪切板图片
  this.$showPasteImage = $('#showPasteImage')
  this.$showPasteCancle = $('#showPasteCancle')
  this.$showPasteConfirm = $('#showPasteConfirm')

  try {
    this.audioContext = new Recorder.AudioContext;
  } catch (e) {
    console.log(e);
  }
  YX.fn.recorder = null;
  YX.fn.recordTimeout = '';
  YX.fn.recordTime = 0;
  YX.fn.senImageBolb = null;


  this.$sendBtn.on('click', this.sendTextMessage.bind(this));
  this.$messageText.on('keydown', this.inputMessage.bind(this));
  //粘贴事件
  this.$messageText.on('paste', this.inputPasteMessage.bind(this));
  this.$showPasteCancle.on('click',this.showPasteCancleFun.bind(this));
  this.$showPasteConfirm.on('click',this.showPasteConfirmFun.bind(this));

  this.$chooseFileBtn.on('click', 'a', this.chooseFile.bind(this));
  this.$fileInput.on('change', this.uploadFile.bind(this));
  this.$toRecord.on('click', this.recordAudio.bind(this));
  this.$cancelRecord.on('click', this.cancelRecordAudio.bind(this));
  this.$showNetcallAudioLink.on('click', this.stopRecordAndAudio.bind(this));
  this.$showNetcallVideoLink.on('click', this.stopRecordAndAudio.bind(this));
  this.$showWhiteboard.on('click', this.stopRecordAndAudio.bind(this));

  // $('#nickName').on('click',this.testOpen.bind(this))

  //结束咨询服务模块
  this.$endserviceBtn.on('click',this.endserviceBtnFun.bind(this))
  //消息重发
  this.$chatContent.delegate('.j-resend', 'click', this.doResend.bind(this));
  //语音播发
  this.$chatContent.delegate('.j-mbox', 'click', this.playAudio);
  //点击显示合同模板
  this.$chatContent.delegate('.u-112-info','click',this.showContactTemplate.bind(this))
  //点击去生成评估报告
  this.$chatContent.delegate('.u-111-info','click',this.assessmentReport.bind(this))
  //常用功能点击按钮
  $("#commonFunctions").on("click",function(e){
    $(".far-right-panel .far-right-order").addClass("hide");
    $(".far-right-panel .far-right-tools").removeClass("hide");
    $("#cloudMsgContainer").addClass('hide');
  })
  //关闭常用功能
  $(".far-right-panel .far-right-tools .far-title-title img").on("click",function(e){
    $(".far-right-panel .far-right-order").removeClass("hide")
    $(".far-right-panel .far-right-tools").addClass("hide")
  })

  //点击常用功能跳转
  $(".far-right-tools .far-tools-info .tool-block").on("click",function(e){
    console.log("e===",e)
    let type = e.currentTarget.dataset.type;
    switch(type){
      case 'cgs':
        window.open(websiteUrl + '/searchCompany')
        break
      case 'cal':
        window.open(websiteUrl + '/searchCase')
        break
      case 'cfg':
        window.open(websiteUrl + '/searchLawRule')
        break
      case 'zzq':
        window.open(websiteUrl + '/searchGraph')
        break
      case 'sls':
        window.open(websiteUrl + '/lawyer')
        break
      case 'ls':
        window.open(websiteUrl + '/calculator/lsf')
        break
      case 'ss':
        window.open(websiteUrl + '/calculator/ssf')
        break
      case 'ts':
        window.open(websiteUrl + '/calculator/ts')
        break
      case 'lx':
        window.open(websiteUrl + '/calculator/lx')
        break
      case 'gs':
        window.open(websiteUrl + '/calculator/gs')
        break
      case 'jj':
        window.open(websiteUrl + '/calculator/jjbc')
        break
      case 'zn':
        window.open(websiteUrl + '/calculator/znj')
        break
      default:
        window.open(websiteUrl);
        break
    }
    
  })


//发送订单
this.$sendQuickOrderWrap.delegate('.order-type .oritem','click',this.sendOrderMessage.bind(this))
$('#sendQuickOrder').on('click',this.showSendOrderFun.bind(this))
$(document).on('click',':not(#sendQuickOrderWrap)',function(e){
  if(!$("#sendQuickOrderWrap").hasClass("hide")){
    $("#sendQuickOrderWrap").addClass("hide");
  }
  return;
})
$('#sendQuickOrderWrap .ort').on('click',function(){
  if(!$("#sendQuickOrderWrap").hasClass("hide")){
    $("#sendQuickOrderWrap").addClass("hide");
  }
})




  //发送常用语
  this.$comonWordsWrap.delegate('.common-items li','click',this.sendCommonWordsFun.bind(this))
  this.$chatContent.delegate('.u-113-bom span','click',this.showSendCommonWordsFun.bind(this))
  $('#comonWords').on('click',this.showSendCommonWordsFun.bind(this))
  $(document).on('click',':not(#comonWordsWrap)',function(e){
    if(!$("#comonWordsWrap").hasClass("hide")){
      $("#comonWordsWrap").addClass("hide");
    }
    return;
  })
  //删除常用语
  $(".common-alert-editIteminfo").delegate(".alert-edit-items .items-right-label-del",'click',(e)=>{
      let id = e.currentTarget.dataset.id; 
      //开始调用服务
      var _that = this;
      //开始调用赢火虫内部服务的接口
      var bodyInfo = {}
      firefly_IM_request.getRequest("delete","/CommonWords/"+id,{},function(res){
          // console.log("删除====",res)
          if(res.isSuccess == "T"){
            topTipGlobalMsg("删除成功！",1500,'success');
            var bodyInfo = {
              lawyerUserId:sessionStorage.getItem("userId"),
            }
            let _this = _that;
            firefly_IM_request.getRequest("get","/CommonWords/list",bodyInfo,function(res){
                if(res.isSuccess == "T" && res.body.length >0){
                  _this.renderCommonWordsList(res.body)
                }
            },function(res){
        
            },'lawyerConsult');
          }else{
          }
      },function(res){
      },'lawyerConsult');
  })

  //置顶常用语
  $(".common-alert-editIteminfo").delegate(".alert-edit-items .items-right-label-top",'click',(e)=>{
    let id = e.currentTarget.dataset.id; 
    //开始调用服务
    var _that = this;
    let commonWordsList = this.commonWordsList;
    let temArr = [],temData = {};
    //重新排序
    for(let i =0;i<commonWordsList.length;i++){
      if(commonWordsList[i].id == id){
        temData = commonWordsList[i];
      }else{
        temArr.push(commonWordsList[i])
      }
    }
    temArr.unshift(temData)
    var bodyInfo = {
      lawyerServiceCommonWords:[...temArr]
    }
    firefly_IM_request.getRequest("post","/CommonWords/changeSort",bodyInfo,function(res){
        // console.log("排序====",res)
        if(res.isSuccess == "T"){
          topTipGlobalMsg("置顶成功！",1500,'success');
          var bodyInfo = {
            lawyerUserId:sessionStorage.getItem("userId"),
          }
          let _this = _that;
          firefly_IM_request.getRequest("get","/CommonWords/list",bodyInfo,function(res){
              if(res.isSuccess == "T" && res.body.length >0){
                _this.commonWordsList = res.body;
                _this.renderCommonWordsList(res.body)
              }
          },function(res){
      
          },'lawyerConsult');
        }else{
        }
    },function(res){
    },'lawyerConsult');
})

 //编辑常用语
 $(".common-alert-editIteminfo").delegate(".alert-edit-items .items-right-label-edit",'click',function(e){
 
  $(this).parents('.alert-edit-items').addClass("active")
  getC($(this).parent().parent().siblings(".edit-contenteditable"))
  $(this).parent().addClass("hide")
  $(this).parent().siblings(".items-right-slabel").removeClass("hide")
  //限制字数为120
  let $content = $(this).parent().parent().siblings(".edit-contenteditable");
  $content.on('keyup input propertychange', function (event) {
    let _words = $(this).text();
    $(this).text(_words.substring(0, 120))
    getC($(this))
  });

})

 //保存常用语
 let __this = this
 $(".common-alert-editIteminfo").delegate(".alert-edit-items .items-right-label-save",'click',function(e){
  // console.log($(this).parent().parent().siblings(".edit-contenteditable")[0].innerText)
  let val = $(this).parent().parent().siblings(".edit-contenteditable")[0].innerText;
  let id = e.currentTarget.dataset.id; 
  var bodyInfo = {}
  __this.commonWordsList.forEach((e)=>{
    if(e.id == id){
      bodyInfo = e;
    }
  })
  bodyInfo.content = val
    //开始调用服务
    var __that = __this;
    firefly_IM_request.getRequest("put","/CommonWords/"+id,bodyInfo,function(res){
        console.log("编辑成功====",res)
        if(res.isSuccess == "T"){
          topTipGlobalMsg("编辑成功！",1500,'success');
          $(this).parents('.alert-edit-items').removeClass("active")
          var bodyInfo = {
            lawyerUserId:sessionStorage.getItem("userId"),
          }
          let ___that = __that;
          firefly_IM_request.getRequest("get","/CommonWords/list",bodyInfo,function(res){
              if(res.isSuccess == "T" && res.body.length >0){
                ___that.renderCommonWordsList(res.body)
              }
          },function(res){
      
          },'lawyerConsult');
        }else{
        }
    },function(res){
    },'lawyerConsult');
})

  //添加常用语
  $('#common_add').on('click',function(e){
    console.log(__this.commonWordsList.length)
    if(__this.commonWordsList.length >= 10){
      topTipGlobalMsg("常用语最多只能添加10条！",1200)
      return
    }
    $(".common-min-alert-mask").addClass("active")
    $(".common-alert-addinfo").removeClass("hide")
    $(".common-alert-editinfo").addClass("hide")
    $(".common-alert-title span").text("添加常用语")
  })
  //关闭常用语弹框
  $("#commonAlertClose").on('click',function(e){
    $(".common-min-alert-mask").removeClass("active")
    $(".common-alert-addinfo").addClass("hide")
  })
  //编辑常用语
  $("#common_edit").on('click',(e)=>{
    $(".common-min-alert-mask").addClass("active")
    $(".common-alert-editinfo").removeClass("hide")
    $(".common-alert-title span").text("编辑常用语")
    this.renderCommonWordsList(this.commonWordsList);
  })

  //保存常用语
  $("#alert-bottom-btn-save").on("click",function(e){
    let val = $("#common-alert-msg").val();
    if(!val){
      topTipGlobalMsg("请输入常用语",2000)
      return
    }

    //开始调用服务
    var _that = this;
    //开始调用赢火虫内部服务的接口
    var bodyInfo = {
      lawyerUserId:sessionStorage.getItem("userId"),
      content:val
    }
    
    firefly_IM_request.getRequest("post","/CommonWords",bodyInfo,function(res){
        // console.log("res====",res)
        if(res.isSuccess == "T"){
          $(".common-min-alert-mask").removeClass("active")
          $(".common-alert-addinfo").addClass("hide")
          topTipGlobalMsg("添加成功！",1500,'success')
        }else{
          
        }
    },function(res){

    },'lawyerConsult');
  })





  //图片显示
  this.$chatBox = $("#chatBox");
  this.$chatBox.delegate('.j-msg .box .cnt a img', 'click', this.showChatImageView.bind(this))
  $("#cloudMsgContainer").delegate('.j-msg .box .cnt a img', 'click', this.showcloudMsgImageView.bind(this))

  //聊天面板右键菜单
  $.contextMenu({
      selector: '.j-msg',
      callback: function(key, options) {
        if (key === 'delete') {
          var id = options.$trigger.parent().data('id');
          var msg = this.cache.findMsg(this.crtSession, id);
          if (!msg || options.$trigger.hasClass('j-msg')) {}
          if (msg.flow !== 'out' && msg.scene === 'p2p') {
            topTipGlobalMsg("点对点场景，只能撤回自己发的消息",2000)
            return;
          }
          if (
            !this.cache.isCurSessionTeamManager &&
            msg.flow !== 'out' &&
            msg.scene === 'team'
          ) {
            topTipGlobalMsg("群会话场景，非管理员不能撤回别人发的消息",2000)
            return;
          }
          options.$trigger.removeClass('j-msg');
          this.nim.deleteMsg({
            msg: msg,
            done: function(err) {
              options.$trigger.addClass('j-msg');
              if (err) {
                if (err.code === 508) {
                  topTipGlobalMsg("发送时间超过2分钟的消息，不能被撤回!",2000)
                } else {
                  topTipGlobalMsg(err.message || '操作失败',2000)
                }
              } else {
                msg.opeAccount = userUID;
                this.backoutMsg(id, {
                  msg: msg
                });
              }
            }.bind(this)
          });
        }
      }.bind(this),
      items: {
        delete: {
          name: '撤回',
          icon: 'delete'
        }
      }
    });

    //表情贴图模块
    this.initEmoji();
  };


// YX.fn.testOpen = function(){
  // alert(1)
  // this.mysdk.addFriend('0424757899e97757842441eadc76eaab',()=>{
    // let _this = this;
    // this.mysdk.insertLocalSession('p2p','0424757899e97757842441eadc76eaab',function(error, obj){
    //   console.log('插入本地会话记录' + (!error?'成功':'失败'), error, obj);
    //   if (!error) {
     
    //   }
    // })
    // this.openChatBox('0424757899e97757842441eadc76eaab','p2p')
  // })
  
// }

//渲染编辑常用消息列表
YX.fn.renderCommonWordsList = function(list){
  //显示相关列表
  if(list.length > 0){
    let temp = [];
    list.forEach((e)=>{
      temp.push(`
          <div class="alert-edit-items">
            <div contenteditable="true" class="edit-contenteditable">${e.content}</div>
            <div class="alert-items-right">
              <span class="items-right-label">
                <span class="items-right-label-edit" data-id="${e.id}">编辑</span>
                <span class="items-right-label-del" data-id="${e.id}">删除</span>
                <span class="items-right-label-top" data-id="${e.id}">置顶</span>
              </span>
              <span class="items-right-slabel hide">
                <span class="items-right-label-save" data-id="${e.id}">保存</span>
              </span>
            </div>
          </div>
      `)
    })
    $(".common-alert-editIteminfo").html(temp.join(""))
  }
}


//显示合同模板
YX.fn.showContactTemplate = function(e){
  window.open(e.currentTarget.dataset.url,'_blank')
}

//生成评估报告
YX.fn.assessmentReport = function(e){
  console.log("关联参数=====",e.currentTarget.dataset)
}

//聊天图片显示
YX.fn.showChatImageView = function(o){
  if($("#moniShowImageId")){
    $("#moniShowImageId").remove();
  }
  var obj = document.createElement('ul');
  obj.setAttribute("id","moniShowImageId");
  obj.setAttribute('style', 'display:none');
  var pinShowIndex = 0;
  // if(showChatImageList.length > 0){
  //     showChatImageList.forEach(function(e,index){
  //       var liobj = document.createElement('li');
  //         liobj.innerHTML="<img id='"+index+'imgshow'+"' src='"+e+"'>";
  //       obj.appendChild(liobj)
  //       if(e == o.currentTarget.dataset.src){
  //         pinShowIndex = index;
  //       }
  //   });
  // }
  // 目前只显示当前图片
  var liobj = document.createElement('li');
      liobj.innerHTML="<img id='"+0+'imgshow'+"' src='"+o.currentTarget.dataset.src+"'>";
      obj.appendChild(liobj)

  document.body.append(obj)
  var _Viewer=window.Viewer;
  var ImgViewer = new _Viewer(obj, {
      // url:"data-original",
      hidden: function () {
          ImgViewer.destroy();
      },
      // viewed: function () {
      //   ImgViewer.view(pinShowIndex);
      // }
  });
setTimeout(function(){
  $("#"+pinShowIndex+"imgshow").click();
},100);
  // ImgViewer.show();
}

YX.fn.showcloudMsgImageView = function(o){
  if($("#moniShowImageId")){
    $("#moniShowImageId").remove();
  }
  var obj = document.createElement('ul');
  obj.setAttribute("id","moniShowImageId");
  obj.setAttribute('style', 'display:none');
  var liobj = document.createElement('li');
  liobj.innerHTML="<img src="+o.currentTarget.dataset.src+">";
  obj.appendChild(liobj)
  document.body.append(obj)
  var _Viewer=window.Viewer;
  var ImgViewer = new _Viewer(obj, {
      hidden: function () {
          ImgViewer.destroy();
      },
      navbar:false,
      // toolbar:false
  });
  ImgViewer.show();
}

/**
 * 
 *  处理图片粘贴事件
 * 
 */
YX.fn.inputPasteMessage = function(e){
  // 添加到事件对象中的访问系统剪贴板的接口
  var clipboardData = e.originalEvent.clipboardData,
    i = 0,
    items, item, types;

  if( clipboardData ){
    items = clipboardData.items;
    // console.log("items=====",items)
    if( !items ){
      return;
    }
    item = items[0];
    // 保存在剪贴板中的数据类型
    types = clipboardData.types || [];
    for( ; i < types.length; i++ ){
      if( types[i] === 'Files' ){
        item = items[i];
        break;
      }
    }
    // 判断是否为图片数据
    if( item && item.kind === 'file' && item.type.match(/^image\//i) ){
     if(this.$showPasteImage.hasClass('hide')){
        //此时需要显示图片显示层
        this.$mask.removeClass('hide')
        this.$showPasteImage.removeClass('hide')
        this.readPasteShowImg( item );
     }
    }
  }
}

YX.fn.readPasteShowImg = function(item){
  var blob = item.getAsFile(),
      reader = new FileReader();
      YX.fn.senImageBolb = reader;
      // 读取文件后将其显示在网页中
      reader.onload = function( e ){
        console.log("e截图的文件=",e)
        var img = new Image();
        img.src = e.target.result;
        $('.showContentImg').append( img );
      };
      // 读取文件
      // console.log("剪切返回=",reader.readAsDataURL( blob ))
      reader.readAsDataURL( blob );
}

//取消剪切板图层
YX.fn.showPasteCancleFun = function(){
  this.$showPasteImage.addClass('hide')
  this.$mask.addClass('hide')
  $('.showContentImg').html("");
}

//确认提交图层
YX.fn.showPasteConfirmFun = function(){
  var dataURL = $('.showContentImg img')[0].src;
  var that = this,
    scene = this.crtSessionType,
    to = this.crtSessionAccount;
  this.$showPasteImage.addClass('hide')
  this.$mask.addClass('hide')
  $('.showContentImg').html("");
  this.mysdk.sendImageMessage(scene, to, dataURL, this.sendMsgDone.bind(this));
}

//查询咨询订单
YX.fn.showSendOrderFun = function(e){
  e.stopPropagation()
  //开始调用服务
  let _this = this;
  //开始调用赢火虫内部服务的接口
  var bodyInfo = {
    productCodeList:['picture_consult','phone_consult']
  }
  
  firefly_IM_request.getRequest("post","/winCoins/winCoinProducts/batch",bodyInfo,function(res){
    console.log("咨询订单=",res)
      if(res.isSuccess == "T" && res.body.length >0){
        // _that.commonWordsList = res.body;
        let temp = []
        res.body.forEach((e)=>{
         
          temp.push(`
            <div class="oritem" data-info=${JSON.stringify(e)}>
              <div class="irt">
                <img src="./images/${e.productCode == "picture_consult"?'tw.png':'dh.png'}" alt="" class="rim">
                <div class="rms">
                  <p class="bt">${e.productDesc}</p>
                  <p class="sj">¥${e.costAmt}元/${e.serviceMode}</p>
                </div>
              </div>
              <img src="./images/rjt.png" alt="" class="rjt">
            </div>
          `)
        
      })
      $("#sendQuickOrderWrap .order-type").html(temp.join(''))
      _this.$sendQuickOrderWrap.removeClass("hide")
    }
  },function(res){

  },'wincoin');
}

//查询常用语弹框
YX.fn.showSendCommonWordsFun = function(e){
    e.stopPropagation()
    //开始调用服务
    var _that = this;
    //开始调用赢火虫内部服务的接口
    var bodyInfo = {
      lawyerUserId:sessionStorage.getItem("userId"),
    }
    
    firefly_IM_request.getRequest("get","/CommonWords/list",bodyInfo,function(res){
        if(res.isSuccess == "T" && res.body.length >0){
          _that.commonWordsList = res.body;
          let temp = []
          res.body.forEach((e)=>{
            temp.push(`<li>${e.content}</li>`)
          })
          $("#comonWordsWrap .common-items").html(temp.join(''))
          _that.$comonWordsWrap.removeClass("hide")
        }else{
          if(_that.commonWordsList.length > 0){
            let temp = []
            _that.coomonWordsList.forEach((e)=>{
              temp.push(`<li>${e.content}</li>`)
            })
            $("#comonWordsWrap .common-items").html(temp.join(''))
            _that.$comonWordsWrap.removeClass("hide")
          }
        }
    },function(res){

    },'lawyerConsult');
}

//发送常用语
YX.fn.sendCommonWordsFun = function(e){
  let msg = e.currentTarget.innerText; 
  this.$messageText.val(msg);
}

//发送订单消息
YX.fn.sendOrderMessage = function(e){
  // console.log("this==",$(e.target).attr('data-info'))
  let currentstr = $(e.currentTarget).attr('data-info');
  let currentInfo = JSON.parse(currentstr)
  let scene = this.crtSessionType;
  let to = this.crtSessionAccount;
 
  let content={
    "data":{
      "costAmtStr":currentInfo.costAmtStr,
      "productDetail":currentInfo.productDetail,
      "productId":currentInfo.productId,
      "productDesc":currentInfo.productDesc,
      "productType":currentInfo.productType,
      "promotionDesc":currentInfo.promotionDesc,
      "vipPriceStr":currentInfo.vipPriceStr,
      "title":'律师发起了一笔新订单，用户下单后可继续进行咨询。',
      "productCode":currentInfo.productCode,
      "serviceMode":currentInfo.serviceMode,
      "returnCostStr":currentInfo.returnCostStr,
      "preCostStr":currentInfo.preCostStr,

      "from":this.accid,
      "to":to,
      },
      "type":"200"
  }
  // console.log("content==",content)
  this.mysdk.sendCustomMessage(scene, to, content, this.sendMsgDone.bind(this));
}





//提交结束服务消息
YX.fn.endserviceBtnFun = function(){

  // if(parseInt(YX.fn.tuWenTimes) <= 1800){
  //   topTipGlobalMsg("咨询服务暂未结束，无法完成服务!",2000)
  //   return
  // }
   //开始调用服务
   var _that = this;
  window.minAlert.alert({
    type: 'warnning',
    title:"确定已解答完用户的咨询问题？",
    msg:"经过用户确认后，此订单将会服务完成",
    cancelBtnMsg: '继续服务', //取消按钮的按钮内容
    confirmBtnMsg:'确定完成', //确定按钮的按钮内容
    showConfirm:true,
    cbConfirm: function(){
      //开始调用赢火虫内部服务的接口
      let sendData = {
        "lawyerServiceId":_that.haveInHandConsultId
      }
      firefly_IM_request.getRequest("post","/lawyerService/lawyer/finish",sendData,function(res){
        console.log("结束服务res====",res)
        if(res.isSuccess == "T"){
          if(YX.fn.serveceConsultTime){
            clearInterval(YX.fn.serveceConsultTime)
          }
          //隐藏倒计时模块
          $(".zx-time-cutdown").addClass("hide")
          _that.getOrderDet(_that.otherAccid);
        }else{
          
        }
    },function(res){

    },'lawyerConsult');
    }
  });
  
   
  // var that = this,
  // scene = this.crtSessionType,
  // to = this.crtSessionAccount;
  // //结束服务
  // let content={
  //   "data":{
  //     "titleFrom":'已结束服务',
  //     "titleTo":'黄小明律师 已结束当前服务',
  //     "msgFrom":"图文咨询已结束，感谢您的支持。",
  //     "msgTo":"图文咨询已结束，感谢您的支持。",
  //     "btnStatus":0,
  //     "from":this.accid,
  //     "to":to,
  //     },
  //     "type":"113"
  // }

  //合同模板
  // let content={
  //   "data":{
  //     "title":'离婚协议书参考标准范本',
  //     "iconUrl":"https://winhc.oss-cn-shanghai.aliyuncs.com/word_icon.png",
  //     "url":"https://winhc.oss-cn-shanghai.aliyuncs.com/20171122103726_5525619277063134594555.doc",
          // "downLoadUrl":"",
  //     "from":this.accid,
  //     "to":to,
  //     },
  //     "type":"112"
  // }

  //履债评估
  // let content={
  //   "data":{
  //     "diagnosisId":'1111',
  //     "debtorName":"123,222",
  //     "score":90,
  //     "grade":'A',
  //     "caseAmt":1000,
  //     "result":"测试测试",
  //     "btnStatus":0,
  //     "from":this.accid,
  //     "to":to,
  //     },
  //     "type":"111"
  // }

  //看法规
  // let content = {
  //   "data":{
  //     "title":"相关法律法规",
  //     "content":"按照现行法律规定，共享单车运营企业一旦进入破产程序，消费者的押金因为属于一般债权，不会优先予以清偿。破产费用、职工工资、国家税收等属于优先清偿的债权范筹，如果破产债权不足以支付这些费用的话，破产程序就停止了。如果这些债权清偿完后还有钱的话，那就清偿优先债权有抵押债权的债权。这些债权清偿完了，那才是一般债权。",
  //     "from":this.accid,
  //     "to":to,
  //   },
  //   "type":'114'

  // }
  // this.mysdk.sendCustomMessage(scene, to, content, this.sendMsgDone.bind(this));
}


/**
 * 处理收到的消息
 * @param  {Object} msg
 * @return
 */
YX.fn.doMsg = function(msg) {
  //根据系统推送结束消息结当前聊天
   if(msg.tip == '当前咨询服务已结束' && (msg.from + msg.to) == (this.accid + this.otherAccid)){
        if(this.serveceConsultTime){
          clearInterval(this.serveceConsultTime)
        }
        //隐藏倒计时模块
        $(".zx-time-cutdown").addClass("hide")
        this.getOrderDet(this.otherAccid);
    }



  var that = this,
    who = msg.to === userUID ? msg.from : msg.to,
    updateContentUI = function() {
      //如果当前消息对象的会话面板打开
      if (that.crtSessionAccount === who) {
        that.sendMsgRead(who, msg.scene);
        that.cache.dealTeamMsgReceipts(msg, function() {
          var msgHtml = appUI.updateChatContentUI(msg, that.cache);
          that.$chatContent.find('.no-msg').remove();
          that.$chatContent.append(msgHtml).scrollTop(99999);
        })
      }
    };
  //非群通知消息处理
  if (/text|image|file|audio|video|geo|custom|tip|robot/i.test(msg.type)) {
    this.cache.addMsgs(msg);
    var account = msg.scene === 'p2p' ? who : msg.from;
    //用户信息本地没有缓存，需存储
    if (!this.cache.getUserById(account)) {
      this.mysdk.getUser(account, function(err, data) {
        if (!err) {
          that.cache.updatePersonlist(data);
          updateContentUI();
        }
      });
    } else {
      this.buildSessions();
      updateContentUI();
    }
    //桌面消息提醒
    // console.log("是否关闭桌面通知isCloseDesktopTip======",sessionStorage.getItem("isCloseDesktopTip"))
    // console.log("当前窗口隐藏状态windowVisibility======",sessionStorage.getItem("windowVisibility"))
    if(sessionStorage.getItem("isCloseDesktopTip") != "true"){
      var windowVisibility = sessionStorage.getItem("windowVisibility")
      if(msg.scene === 'p2p' && windowVisibility == 'hidden'){
        this.sysDesktopMsgTip(msg)
      }
    }
    
  } else {
    // 群消息处理
    console.log("监听群消息=",msg)
    //监听会话面板上群组人员的数量
    // if(msg.attach.users){
    //   that.$memberNum.text("( "+msg.attach.users.length+" )");
    // }
    this.messageHandler(msg, updateContentUI);
  }
};
/*****************************************************************
 * emoji模块
 ****************************************************************/
YX.fn.initEmoji = function() {
  this.$showEmoji = $('#showEmoji');
  this.$showEmoji.on('click', this.showEmoji.bind(this));
  var that = this,
    emojiConfig = {
      emojiList: emojiList, //普通表情
      pinupList: pinupList, //贴图
      width: 500,
      height: 300,
      imgpath: './images/',
      callback: function(result) {
        that.cbShowEmoji(result);
      }
    };
  this.$emNode = new CEmojiEngine($('#emojiTag')[0], emojiConfig);
  this.$emNode._$hide();
};
/**
 * 选择表情回调
 * @param  {objcet} result 点击表情/贴图返回的数据
 */
YX.fn.cbShowEmoji = function(result) {
  if (!!result) {
    var scene = this.crtSessionType,
      to = this.crtSessionAccount;
    // 贴图，发送自定义消息体
    if (result.type === 'pinup') {
      var index = Number(result.emoji) + 1;
      var content = {
        type: 3,
        data: {
          catalog: result.category,
          chartlet: result.category + '0' + (index >= 10 ? index : '0' + index)
        }
      };
      this.mysdk.sendCustomMessage(
        scene,
        to,
        content,
        this.sendMsgDone.bind(this)
      );
    } else {
      // 表情，内容直接加到输入框
      this.$messageText[0].value = this.$messageText[0].value + result.emoji;
    }
  }
};

YX.fn.showEmoji = function() {
  this.$emNode._$show();
};
/*************************************************************************
 * 发送消息逻辑
 *
 ************************************************************************/
YX.fn.uploadFile = function() {
  var that = this,
    scene = this.crtSessionType,
    to = this.crtSessionAccount,
    fileInput = this.$fileInput.get(0);
  if (fileInput.files[0].size == 0) {
    layer.msg("不能传空文件",{icon:0})
    return;
  }
  // console.log("上传文件的相关信息=",fileInput.value)
  this.mysdk.sendFileMessage(scene, to, fileInput, this.sendMsgDone.bind(this));
};

YX.fn.chooseFile = function() {
  this.$fileInput.click();
};

YX.fn.sendTextMessage = function() {
  var self = this
  if (self.$toRecord.hasClass('recording') || self.$toRecord.hasClass('recorded')) {
    if (YX.fn.recordTime < 2) {
      layer.msg("语音消息最短2s",{icon:0})
      return
    }
    self.stopRecordAudio()
    self.sendRecordAudio()
    return
  }
  var scene = this.crtSessionType,
    to = this.crtSessionAccount,
    text = this.$messageText.val().trim();
  if (!!to && !!text) {
    if (text.length > 1500) {
      layer.msg("消息长度最大为1500字符",{icon:0})
    } else if (text.length === 0) {
      return;
    } else {
      var options = {
        scene: scene || 'p2p',
        to: to,
        text: text,
        done: this.sendMsgDone.bind(this)
      };
      // 客户端反垃圾检查
      var ret = nim.filterClientAntispam({
        content: text
      });

      switch (ret.type) {
        case 0:
          // console.log('没有命中反垃圾词库', ret.result);
          break;
        case 1:
          // console.log('已对特殊字符做了过滤', ret.result);
          options.text = ret.result;
          break;
        case 2:
          // console.log('建议拒绝发送', ret.result);
          this.mysdk.sendTipMsg({
            scene: scene,
            to: to,
            tip: '命中敏感词，拒绝发送'
          });
          return;
        case 3:
          // console.log('建议服务器处理反垃圾，发消息带上字段clientAntiSpam';
          options.clientAntiSpam = true;
          break;
      }
      if (
        this.crtSessionType === 'team' &&
        this.crtSessionTeamType === 'advanced'
      ) {
        // if ($('#needTeamMsgReceipt') && $('#needTeamMsgReceipt')[0].checked) {
          options.needMsgReceipt = true;
        // }
      }
      this.nim.sendText(options);
    }
  }
};

YX.fn.sendRecordAudio = function() {
  var self = this
  YX.fn.recorder.exportWAV(function(blob) {
    self.$toRecord.addClass('uploading');
    self.nim.sendFile({
      scene: self.crtSessionType,
      to: self.crtSessionAccount,
      type: 'audio',
      blob: blob,
      uploadprogress: function(obj) {
        console.log('文件总大小: ' + obj.total + 'bytes');
        console.log('已经上传的大小: ' + obj.loaded + 'bytes');
        console.log('上传进度: ' + obj.percentage);
        console.log('上传进度文本: ' + obj.percentageText);
        if (obj.percentage === 100) {
          self.$toRecord.removeClass('uploading');
          self.$toRecord.removeClass('recorded');
        }
      },
      done: self.sendMsgDone.bind(self)
    });
  });
  self.cancelRecordAudio()
}

YX.fn.stopRecordAndAudio = function () {
  YX.fn.stopRecordAudio()
  YX.fn.stopPlayAudio()
}
YX.fn.recordAudio = function() {
  YX.fn.stopPlayAudio()
  var self = this
  if (location.protocol === 'http:') {
    layer.msg("请使用https协议",{icon:0})
    return
  }
  if (!self.audioContext) {
    layer.msg("当前浏览器不支持录音!",{icon:0})
    return
  }
  if (!self.$toRecord.hasClass('recording') && !self.$toRecord.hasClass('recorded')) {
    if (YX.fn.recorder) {
      YX.fn.recorder.clear();
      YX.fn.recorder.record();
      self.showRecorderTime()
    } else {
      Recorder.mediaDevices.getUserMedia({
        audio: true
      }).then(function(stream) {
        var input = self.audioContext.createMediaStreamSource(stream);
        YX.fn.recorder = new Recorder(input);
        YX.fn.recorder.record();
        if (~self.audioContext.state.indexOf('suspend')) {
          self.audioContext.resume().then(function () {
            YX.fn.recorder.record();
            self.showRecorderTime()
            console.log('audioContext suspend state resume');
          })
        } else {
          self.showRecorderTime()
        }
      }).catch(function(err) {
        layer.msg("您没有可用的麦克风输入设备",{icon:0})
        self.$toRecord.addClass('disabled')
        console.log('No live audio input: ' + err, err.name + ": " + err.message);
      });
    }
  }
}
YX.fn.showRecorderTime = function () {
  var self = this
  if (YX.fn.recorder) {
    self.$recordTimeBox.show()
    self.$toRecord.addClass('recording');
    YX.fn.recordTime = 0;
    YX.fn.recordTimeout = setTimeout(self.recordTimeRun.bind(self), 1000)
  }
}
YX.fn.recordTimeRun = function () {
  var self = this
  YX.fn.recordTimeout = setTimeout(self.recordTimeRun.bind(self), 1000)
  YX.fn.recordTime++;
  if (YX.fn.recordTime >= 60) {
    clearTimeout(YX.fn.recordTimeout)
    self.stopRecordAudio()
  }
  self.$recordTimeDuration.html('00:' + (YX.fn.recordTime > 9 ? YX.fn.recordTime : '0' + YX.fn.recordTime))
}
YX.fn.stopRecordAudio = function() {
  var $toRecord = $('#toRecord')
  var isRecording = $toRecord.hasClass('recording');
  if (isRecording) {
    $toRecord.removeClass('recording');
    $toRecord.addClass('recorded');
    if (YX.fn.recorder) {
      clearTimeout(YX.fn.recordTimeout)
      YX.fn.recorder.stop();
    }
  }
}

YX.fn.cancelRecordAudio = function () {
  var $toRecord = $('#toRecord')
  var isRecording = $toRecord.hasClass('recording') || $toRecord.hasClass('recorded');
  var $recordTimeBox = $('#toRecordBox')
  var $recordTimeDuration = $('#toRecordTime')
  if (isRecording && YX.fn.recorder) {
    clearTimeout(YX.fn.recordTimeout)
    YX.fn.recorder.stop();
    YX.fn.recorder.clear();
    $recordTimeBox.hide()
    $toRecord.removeClass('recording');
    $toRecord.removeClass('recorded');
    $recordTimeDuration.html('00:00')
    YX.fn.recordTime = 0
  }
}
/**
 * 发送消息完毕后的回调
 * @param error：消息发送失败的原因
 * @param msg：消息主体，类型分为文本、文件、图片、地理位置、语音、视频、自定义消息，通知等
 */
YX.fn.sendMsgDone = function(error, msg) {
  if (error && error.code === 7101) {
    layer.msg("被拉黑",{icon:0})
    msg.blacked = true;
  }
  this.cache.addMsgs(msg);
  if (msg.type === 'text') {
    this.$messageText.val('');
  }
  this.$chatContent.find('.no-msg').remove();
  this.cache.dealTeamMsgReceipts(msg, function() {
    var msgHtml = appUI.updateChatContentUI(msg, this.cache);
    this.$chatContent.append(msgHtml).scrollTop(99999);
    $('#uploadForm')
      .get(0)
      .reset();
  }.bind(this))
};

YX.fn.inputMessage = function(e) {
  var ev = e || window.event;
  if ($.trim(this.$messageText.val()).length > 0) {
    if (ev.keyCode === 13 && ev.ctrlKey) {
      this.$messageText.val(this.$messageText.val() + '\r\n');
    } else if (ev.keyCode === 13 && !ev.ctrlKey) {
      this.sendTextMessage();
    }
  }
};
// 重发
YX.fn.doResend = function(evt) {
  var $node;
  if (evt.target.tagName.toLowerCase() === 'span') {
    $node = $(evt.target);
  } else {
    $node = $(evt.target.parentNode);
  }
  var sessionId = $node.data('session');
  var idClient = $node.data('id');
  var msg = this.cache.findMsg(sessionId, idClient);
  this.mysdk.resendMsg(
    msg,
    function(err, data) {
      if (err) {
        layer.msg(err.message || '发送失败',{icon:0})
      } else {
        this.cache.setMsg(sessionId, idClient, data);
        var msgHtml = appUI.buildChatContentUI(sessionId, this.cache);
        this.$chatContent.html(msgHtml).scrollTop(99999);
        $('#uploadForm')
          .get(0)
          .reset();
      }
    }.bind(this)
  );
};
/************************************************************
 * 获取当前会话消息
 * @return {void}
 *************************************************************/
YX.fn.getHistoryMsgs = function(scene, account) {
  var id = scene + '-' + account;
  var sessions = this.cache.findSession(id);
  var msgs = this.cache.getMsgs(id);

  //标记已读回执
  this.sendMsgRead(account, scene);
  if (!!sessions) {
    // if (sessions.unread >= msgs.length) {
    // var end = msgs.length > 0 ? msgs[0].time : false;
    // }
    // if (sessions.lastMsg) {
    //   var end = sessions.lastMsg.time || false
    // }
    var end = false
    this.mysdk.getLocalMsgs(id, end, this.getLocalMsgsDone.bind(this));
    return;
    // }
  }
  this.doChatUI(id);
};
//拿到历史消息后聊天面板UI呈现
YX.fn.doChatUI = function(id) {
  this.cache.dealTeamMsgReceipts(id, function() {
    var temp = appUI.buildChatContentUI(id, this.cache);
    this.$chatContent.html(temp);
    this.$chatContent.scrollTop(9999);
    //已读回执UI处理
    this.markMsgRead(id);
  }.bind(this));
};

YX.fn.getLocalMsgsDone = function(err, data) {
  if (!err) {
    var reset = true
    this.cache.addMsgsByReverse(data.msgs, true);
    var id = data.sessionId;
    var array = getAllAccount(data.msgs);
    var that = this;
    this.checkUserInfo(array, function() {
      that.doChatUI(id);
    });
  } else {
    layer.msg('获取历史消息失败',{icon:0})
  }
};

//检查用户信息有木有本地缓存 没的话就去拿拿好后在执行回调
YX.fn.checkUserInfo = function(array, callback) {
  var arr = [];
  var that = this;
  for (var i = array.length - 1; i >= 0; i--) {
    if (!this.cache.getUserById(array[i])) {
      arr.push(array[i]);
    }
  }
  if (arr.length > 0) {
    this.mysdk.getUsers(arr, function(error, data) {
      if (!error) {
        that.cache.setPersonlist(data);
        callback();
      } else {
        layer.msg('获取用户信息失败',{icon:2})
      }
    });
  } else {
    callback();
  }
};
//发送已读回执
YX.fn.sendMsgRead = function(account, scene) {
  if (scene === 'p2p') {
    var id = scene + '-' + account;
    var sessions = this.cache.findSession(id);
    this.mysdk.sendMsgReceipt(sessions.lastMsg, function(err, data) {
      if (err) {
        console.log(err);
      }
    });
  }
};
//UI上标记消息已读
YX.fn.markMsgRead = function(id) {
  if (!id || this.crtSession !== id) {
    return;
  }
  var msgs = this.cache.getMsgs(id);
  for (var i = msgs.length - 1; i >= 0; i--) {
    var message = msgs[i];
    // 目前不支持群已读回执
    if (message.scene === 'team') {
      return;
    }
    if (message.type !== 'tip' && window.nim.isMsgRemoteRead(message)) {
      $('.item.item-me.read').removeClass('read');
      $('#' + message.idClient).addClass('read');
      break;
    }
  }
};
//撤回消息
YX.fn.backoutMsg = function(id, data) {
  var msg = data ? data.msg : this.cache.findMsg(this.crtSession, id);
  var to = msg.target;
  var session = msg.sessionId;
  var opeAccount = msg.opeAccount || msg.from;
  var opeNick = getNick(opeAccount);
  if (msg.scene === 'team') {
    var teamId = msg.to || this.crtSessionAccount;
    var teamInfo = this.cache.getTeamById(teamId);
    if (teamInfo && opeAccount !== msg.from) {
      if (teamInfo.owner === opeAccount) {
        opeNick = '群主' + opeNick;
      } else if (teamInfo.type === 'advanced') {
        opeNick = '管理员' + opeNick;
      }
    }
  }else if(msg.scene === 'p2p'){
    opeNick = "对方"
  }

  this.nim.sendTipMsg({
    isLocal: true,
    idClient: msg.idClient || null,
    scene: msg.scene,
    to: to,
    tip: (userUID === opeAccount ? '你' : opeNick) + '撤回了一条消息',
    time: msg.time,
    done: function(err, data) {
      if (!err) {
        this.cache.backoutMsg(session, id, data);
        if (this.crtSession === session) {
          var msgHtml = appUI.buildChatContentUI(this.crtSession, this.cache);
          this.$chatContent.html(msgHtml).scrollTop(99999);
          //已读回执UI处理
          this.markMsgRead(this.crtSession);
        }
      } else {
        layer.msg('操作失败',{icon:2})
      }
    }.bind(this)
  });
};

/*********************************多人音视频模块********************************* */
/** 发送群视频tip消息
 * @param {object} option
 * @param {string} option.teamId 群id
 * @param {string} option.account 发送群视频的uid
 * @param {string} option.message tip消息
 */
YX.fn.sendTeamNetCallTip = function(option) {
  var tmpUser = this.cache.getTeamMemberInfo(option.account, option.teamId);
  option.nick = tmpUser.nickInTeam || getNick(option.account);

  option.isLocal = option.isLocal === undefined ? true : option.isLocal;
  /** 远程 先禁掉 */
  this.nim.sendTipMsg({
    isLocal: option.isLocal,
    scene: 'team',
    to: option.teamId,
    tip: getNick(option.nick) + option.message,
    time: Date.now(),
    isPushable: false,
    isHistoryable: false,
    isRoamingable: false,
    done: function(err, data) {
      // err && console.log(err)
      // this.buildSessions();
      // var msgHtml = appUI.buildChatContentUI(this.crtSession, this.cache)
      this.cache.addMsgs(data);
      var msgHtml = appUI.updateChatContentUI(data, this.cache);
      this.$chatContent.append(msgHtml).scrollTop(99999);
    }.bind(this)
  });
};

/** 对列表用户进行点对点发送自定义系统通知
 * @param {Array} list
 * @param {object} option
 * @param {string} option.caller 主叫人
 * @param {string} option.type 视频还是音频, 如果为空，则取消呼叫!
 * @param {string} option.list 被呼叫uid的列表
 * @param {string} option.teamId 群id
 * @param {string} option.channelName 房间id
 */
YX.fn.sendCustomMessage = function(option) {
  var that = this;
  option.list = option.list || [];

  var tmpUser = this.cache.getTeamMemberInfo(option.caller, option.teamId);
  option.nick = tmpUser.nickInTeam || getNick(option.caller);

  option.list.forEach(function(uid) {
    // this.mysdk.sendCustomMessage('p2p', item, content, this.sendMsgDone.bind(this))
    that.nim.sendCustomSysMsg({
      scene: 'p2p',
      to: uid,
      enablePushNick: false,
      content: JSON.stringify({
        id: 3,
        members: option.list,
        teamId: option.teamId,
        room: option.channelName,
        type: option.type
      }),
      isPushable: true,
      sendToOnlineUsersOnly: false,
      apnsText: option.nick + '正在呼叫您',
      done: function(error, msg) {
        console.log(msg);
      }
    });
  });
};
